<template>
  <div>
    <!-- <v-container class="workflow-container" grid-list-xl fluid> -->
    <div class="super-flow-demo">
      <div class="select-botton">
        <div class="d-flex mb-3">
          <div @click="divshow = 1" :class="divshow == 1 ? 'tab-button-active' : ''" class="tab-button"> 实例化信息</div>
          <!-- <div @click="divshow = 2" :class="divshow == 2 ? 'tab-button-active' : ''" class="tab-button"> 工作流组件 </div> -->
        </div>
      </div>
      <div class="div-moudle">
        <el-card style="height: 100%;">
          <div class="top-div" v-show="divshow == 1">
            <el-form ref="form" size="mini" :model="workForm" label-width="100px">
              <el-row :gutter="23">
                <el-col :span="23">
                  <el-form-item label="工作流名称:">
                    <el-input v-model="workForm.workModelName" placeholder="请输入"
                      :disabled="$route.query.type == 2"></el-input>
                  </el-form-item>
                </el-col>


              </el-row>
              <el-row :gutter="23">

                <el-col :span="23">
                  <el-form-item label="工作流周期:">
                    <el-input v-model="workForm.workTime" placeholder="请输入" :disabled="$route.query.type == 2"></el-input>
                  </el-form-item>
                </el-col>


              </el-row>
              <el-row :gutter="23">

                <el-col :span="23">
                  <el-form-item label="工作流类型:">
                    <el-select v-model="workForm.workModelType" placeholder="请选择设备模型" :disabled="$route.query.type == 2"
                      style="width: 100%;margin-bottom: 5px;">
                      <el-option v-for="item in workModelTypeList" :key="item.configKey" :label="item.configValue"
                        :value="item.configKey">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

              </el-row>
              <el-row :gutter="23">
                <el-col :span="23">
                  <el-form-item label="版本号:">
                    <el-input v-model="workForm.workModelVersion" placeholder="请输入"
                      :disabled="$route.query.type == 2"></el-input>
                  </el-form-item>
                </el-col>

              </el-row>
              <el-row :gutter="23">

                <el-col :span="23">
                  <el-form-item label="工作流描述:">
                    <el-input type="textarea" v-model="workForm.workModelDes" placeholder="请输入"
                      :disabled="$route.query.type == 2"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>


            </el-form>
            <el-form ref="ruleform" size="mini" :rules="slhinfoRules" :model="slhinfoData" label-width="100px">
              <el-row :gutter="23">
                <el-col :span="23">
                  <el-form-item label="实例化名称:" prop="newName">
                    <el-input v-model="slhinfoData.newName" placeholder="请输入"
                      :disabled="$route.query.status == 2"></el-input>
                  </el-form-item>
                </el-col>


              </el-row>

              <el-row :gutter="23">

                <el-col :span="23">
                  <el-form-item label="负责人:" prop="userCodes">
                    <el-select :disabled="$route.query.status == 2" v-model="slhinfoData.userCodes" multiple
                      placeholder="请选择负责人" style="width: 100%;margin-bottom: 5px;">
                      <el-option v-for="item in workModelTypeList" :key="item.userCode" :label="item.userName"
                        :value="item.userCode">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

              </el-row>
              <el-row :gutter="23">
                <el-col :span="23">
                  <el-form-item label="前置条件:">

                  </el-form-item>
                  <div style="height: 420px; overflow-x: hidden;">
                    <el-tag type="info" effect="plain" :key="index" class="mr-3 mb-2"
                      v-for="(item, index) in mapString">{{
                        item.seqValueDes }}
                    </el-tag>
                    <el-button size="mini" @click="handleSLH('前置条件', 'before', 'before')" type="primary">实例化前置条件
                    </el-button>
                  </div>

                </el-col>
              </el-row>

            </el-form>
          </div>
          <div class="right-box" v-show="divshow == 2">
            <div class=" tab-left position-absolute  mt-2 ml-2" style="height:  calc(100vh - 290px);">
              <div class=" p-3">
                <el-form ref="form" :model="workForm" class=" h-100 d-flex flex-column">
                  <el-form-item label="" class=" over-auto ">
                    <div class="d-flex flex-row  flex-wrap  w-100 over-auto col ">
                      <div v-for="(item, index) in nodeItemList" :key="index"
                        class="d-flex flex-column align-items-center">
                        <div class="module-item p-3" @mousedown="(evt) => nodeItemMouseDown(evt, item.value)">
                          <div
                            class="item rounded w-100 h-100 d-flex flex-column align-items-center justify-content-center"
                            style="user-select: none">
                            <img :src="item.img" width="100%" />
                            <!-- <i class="el-icon-eleme text-white" style="font-size:40px;"></i> -->
                          </div>
                        </div>
                        <div class="text-dark">{{ item.label }}</div>
                      </div>
                    </div>
                  </el-form-item>

                </el-form>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <div class="flow-container" ref="flowContainer">
        <super-flow ref="superFlow" :draggable="$route.query.type != 2" :graph-menu="graphMenu"
          :node-menu="$route.query.type != 2 ? nodeMenu : nodeMenuCHAKAN"
          :link-menu="$route.query.type != 2 ? linkMenu : []" :link-desc="linkDesc" :link-base-style="linkBaseStyle"
          :node-list="nodeList" :link-list="linkList">
          <template v-slot:node="{ meta }">
            <div class="flow-node ellipsis flow-node-item d-flex flex-column">
              <div class="p-2 bg-line-light node-title">{{ meta.name }}
                <img v-show="meta.status == 0" src="@/assets/img/Desktop(1)/icon1.png" width="15px" />
                <img v-show="meta.status == 1" src="@/assets/img/Desktop(1)/icon2.png" width="15px" />
                <img v-show="meta.status == 2" src="@/assets/img/Desktop(1)/icon3.png" width="15px" />
              </div>
              <div class="d-flex align-items-center justify-content-between px-2 pointer  col d-flex flex-row">
                <div>{{ meta.placeholder }}</div>
                <i class="el-icon-arrow-right"></i>
              </div>
            </div>
          </template>
        </super-flow>
      </div>
    </div>
    <!-- <div class="super-flow-demo"> -->
    <!-- </div> -->
    <div class="position-relative" style="bottom: 104px;z-index: 99;">
      <div class="position-absolute " style="left: 30px;">
        <div class="d-flex justify-content-center align-items-center" style="width: 240px;height: 80px;">
          <template>
            <el-button type="primary" v-show="$route.query.status != 2" @click="handleRulesSLJ">保存</el-button>
            <el-button type="success" @click="returnUrl()" style="margin-right: 15px;">返回</el-button>
          </template>
        </div>

        <!-- </el-row> -->
      </div>
    </div>
    <el-dialog v-draggable :visible.sync="drawerConf.visible" :close-on-click-modal="false" width="500px">
      <el-form @keyup.native.enter="settingSubmit" @submit.native.prevent v-show="drawerConf.type === drawerType.node"
        ref="nodeSetting" :model="nodeSetting">
        <el-form-item label="node name" prop="name">
          <el-input v-model="nodeSetting.name" placeholder="Please enter the node name" maxlength="30">
          </el-input>
        </el-form-item>
        <el-form-item label="node description" prop="desc">
          <el-input v-model="nodeSetting.desc" placeholder="Please enter a node description" maxlength="30">
          </el-input>
        </el-form-item>
      </el-form>
      <el-form @keyup.native.enter="settingSubmit" @submit.native.prevent v-show="drawerConf.type === drawerType.link"
        ref="linkSetting" :model="linkSetting">
        <!-- <el-input v-model="linkSetting.desc" placeholder="Please enter a link description">
          </el-input> -->
        <el-select v-model="linkSetting.desc" placeholder="请选择" style="width: 100%;margin-bottom: 5px;">
          <el-option key="满足" label="满足" value="满足"></el-option>
          <el-option key="不满足" label="不满足" value="不满足"></el-option>
        </el-select>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="drawerConf.cancel">
          取消
        </el-button>
        <el-button type="primary" @click="settingSubmit">
          确定
        </el-button>
      </span>
    </el-dialog>
    <drawerApprove :flowId="flowId" :listData="capList" ref="drawerApprove" @saveMessage="saveMessage"></drawerApprove>
    <!-- </v-container> -->
    <el-dialog :title="'实例化' + dialogTitle" v-draggable :visible.sync="dialogVisible" width="30%"
      :before-close="handleClose">
      <template v-if="dialogVisible">
        <div class="d-flex p-3" style="height: 320px;overflow:auto;">

          <el-form ref="form" label-width="180px">

            <span class="silclass" v-show="dialogTitle == '逻辑判断'"> {{ ljpdString }}</span>
            <template v-for="i in selectList">
              <el-form-item :label="i.name">
                <el-select :disabled="$route.query.status == 2" v-model="i.value" placeholder="请选择">
                  <el-option v-for="item in i.list" :key="item.deviceCode ? item.deviceCode : item.userCode"
                    :label="item.deviceName ? item.deviceName : item.userName"
                    :value="item.deviceCode ? item.deviceCode : item.userCode">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-form>

        </div>
        <div style="width: 100%; text-align: center;margin-top: 20px;">
          <el-button v-show="$route.query.status != 2" type="primary" @click="saveLogic">保存</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import SuperFlow from "vue-super-flow"
import "vue-super-flow/lib/index.css"
import StartDialog from "./drawer/startDialog.vue"
import SelectDialog from "./dialog/select"
import drawerApprove from "./drawer/approve.vue"
import {
  addMyWorkModel,
  queryProjectAllUser,
  queryTaskDetail,
  updateWorkNewOne,
  queryWorkXLKList,
  queryWorkNewOne,
  queryEnumConfigList,
  queryMyWorkModelOne,
  updateMyWorkModelOne,
  querySysWorkModelOne,
  addMyWorkFromSys,
  insertWorkNewOne,
  queryJudgeNodeDetail
} from "@/api/workflow/index"

const drawerType = {
  node: 0,
  link: 1
}

export default {
  components: {
    SuperFlow,
    StartDialog,
    drawerApprove,
    SelectDialog
  },
  data () {
    return {
      slhinfoRules: {
        newName: [
          { required: true, message: "请输入实例化名称", trigger: "blur" }
        ],

        userCodes: [
          { required: true, message: "请选择负责人", trigger: "change" }
        ]
      },
      divshow: 1,
      mapString: [],
      activeNames: "1",
      dialogVisible: false,
      leftDrawer: true, //左侧抽屉
      workForm: {
        workModelType: ""
      }, //左侧表单
      drawerType,
      // 线条样式
      linkBaseStyle: {
        color: "#BBBBBB", // line 颜色
        hover: "#000", // line hover 的颜色
        textColor: "#666666", // line 描述文字颜色
        textHover: "#FF0000", // line 描述文字 hover 颜色
        font: "14px Arial", // line 描述文字 字体设置 参考 canvas font
        dotted: false, // 是否是虚线
        lineDash: [4, 4], // 虚线时生效
        background: "rgba(255,255,255,0.6)" // 描述文字背景色

      },
      nodeList: [],

      linkList: [],

      drawerConf: {
        title: "",
        visible: false,
        type: null,
        info: null,
        open: (type, info) => {
          const conf = this.drawerConf
          conf.visible = true
          conf.type = type
          conf.info = info
          if (conf.type === drawerType.node) {
            conf.title = "NODE"
            if (this.$refs.nodeSetting) this.$refs.nodeSetting.resetFields()
            this.$set(this.nodeSetting, "name", info.meta.name)
            this.$set(this.nodeSetting, "desc", info.meta.desc)
          } else {
            conf.title = "LINK"
            if (this.$refs.linkSetting) this.$refs.linkSetting.resetFields()
            this.$set(this.linkSetting, "desc", info.meta ? info.meta.desc : "")
          }
        },
        cancel: () => {
          this.drawerConf.visible = false
          if (this.drawerConf.type === drawerType.node) {
            this.$refs.nodeSetting.clearValidate()
          } else {
            this.$refs.linkSetting.clearValidate()
          }
        }
      },
      linkSetting: {
        desc: ""
      },
      nodeSetting: {
        name: "",
        desc: ""
      },
      nodeItemList: [
        //   {
        //   label: '前置条件',
        //   value: () => (
        //     {
        //     width: 140,
        //     height: 70,
        //     meta: {
        //       label: 'start',
        //       name: '前置条件',
        //       type: 'start',
        //       placeholder: '请添加前置条件'
        //     }
        //   })
        // },
        {
          label: "模型开启",
          img: require("@/assets/img/workFlow/Frame 831.png"),
          value: () => ({
            width: 140,
            height: 70,
            meta: {
              desc: "",
              label: "open",
              code: "MD_OPEN",
              name: "模型开启",
              type: "open",
              placeholder: "模型开启"

            }
          })
        }, {
          label: "模型关闭",
          img: require("@/assets/img/workFlow/Frame 832.png"),
          value: () => ({
            width: 140,
            height: 70,
            meta: {
              desc: "",
              label: "close",
              code: "MD_CLOSE",
              name: "模型关闭",
              type: "close",
              placeholder: "模型关闭"
            }
          })
        }, {
          label: "模型参数修改",
          img: require("@/assets/img/workFlow/Frame 834.png"),
          value: () => ({
            width: 140,
            height: 70,
            meta: {
              desc: "",
              label: "update",
              code: "MD_CHANGE",
              name: "模型参数修改",
              type: "update",
              placeholder: "模型参数修改"
            }
          })
        },
        // {
        //   label: '故障数据获取',
        //   value: () => ({
        //     width: 140,
        //     height: 70,
        //     meta: {
        //       label: 'erroe',
        //       name: '故障数据获取',
        //       type: 'erroe',
        //       placeholder: '故障数据获取'
        //     }
        //   })
        // },
        {
          label: "定时器",
          img: require("@/assets/img/workFlow/Frame 835.png"),
          value: () => ({
            width: 140,
            height: 70,
            meta: {
              desc: "",
              label: "timer",
              code: "SYS_TIMER",
              name: "定时器",
              type: "timer",
              placeholder: "请添加时间"
            }
          })
        },

        {
          label: "短信通知",
          img: require("@/assets/img/workFlow/Frame 836.png"),
          value: () => ({
            width: 140,
            height: 70,
            meta: {
              desc: "",
              label: "note",
              code: "SYS_SME",
              name: "短信通知",
              type: "note",
              placeholder: "后续选择被通知人"
            }
          })
        },
        {
          label: "逻辑判断",
          img: require("@/assets/img/workFlow/Frame 837.png"),
          value: () => ({
            width: 140,
            height: 70,
            meta: {
              desc: "",
              label: "logic",
              code: "SYS_JUDGE",
              name: "逻辑判断",
              type: "logic",
              placeholder: "逻辑判断"
            }
          })
        }
      ],
      graphMenu: [
        [{
          label: "选中流程图",
          selected: graph => {
            graph.selectAll()
          }
        }]
      ],
      nodeMenu: [
        [{
          label: "删除",
          hidden: (node) => {
            return node.meta.type == "start"
          },
          selected: node => {
            node.remove()
          }
        },
        {
          label: "编辑",
          hidden: (node) => {
            return node.meta.type == "note"
          },
          selected: node => {
            this.cliNode(node.meta)
            // this.drawerConf.open(drawerType.node, node)
          }
        }
        ]
      ],
      nodeMenuCHAKAN: [
        [
          {
            label: "实例化",
            hidden: (node) => {
              return node.meta.type == "timer"
            },
            selected: node => {
              console.log(node)
              this.handleSLH(node.meta.name, node.id, "detail")
              // this.drawerConf.open(drawerType.node, node)
            }
          }
        ]
      ],
      linkMenu: [
        [{
          label: "删除",

          selected: link => {
            link.remove()
          }
        },
        {
          label: "编辑",
          selected: link => {
            this.drawerConf.open(drawerType.link, link)
          }
        }
        ]
      ],
      dragConf: {
        isDown: false,
        isMove: false,
        offsetTop: 0,
        offsetLeft: 0,
        clientX: 0,
        clientY: 0,
        ele: null,
        info: null
      },
      flowId: "",
      flowMessages: [],
      capList: "",
      flowValue: [],
      workModelTypeList: [],
      workModelCode: "",
      zjList: [],
      dialogTitle: "",
      slhinfoData: {
        newName: "",
        userCodes: []
      },
      selectList: [],
      selectOveryList: {},
      dialogNewType: "",
      dialogSeq: "",
      ljpdString: ""
    }
  },
  created () {
    this.workModelCode = this.$route.query.workModelCode
  },
  mounted () {
    document.addEventListener("mousemove", this.docMousemove)
    document.addEventListener("mouseup", this.docMouseup)
    this.$once("hook:beforeDestroy", () => {
      document.removeEventListener("mousemove", this.docMousemove)
      document.removeEventListener("mouseup", this.docMouseup)
    })
    this.getModeTypeList()
    // this.setDefaultNode()
    if (this.$route.query.type == 2) {
      this.getData()
      if (this.$route.query.status == 0) {
        this.getAllSelect()
      } else {
        this.getslhinfo()
      }

    }
  },

  methods: {
    async getAllSelect () {
      const res = await queryWorkXLKList({ workModelCode: this.$route.query.workModelCode })
      if (res.status == 200) {
        this.selectOveryList = res.object.details
      }
    },
    async getslhinfo () {
      const { status, success, object, message } = await queryWorkNewOne({ newCode: this.$route.query.newCode })
      if (status == "200") {
        this.selectOveryList = object.details
        this.zjList = JSON.parse(object.main.updateByName)
        this.slhinfoData = object.main
        this.slhinfoData.userCodes = object.users.map(v => v.userCode)
      }
    },
    async getLJPDINFO (seq) {
      const res = await queryJudgeNodeDetail({ workModelCode: this.$route.query.workModelCode, seq })
      if (res.status == 200) {
        this.ljpdString = res.object
      }
    },
    handleSLH (name, seq = "", newType) {
      this.dialogTitle = name
      this.dialogVisible = true
      this.dialogSeq = seq
      this.dialogNewType = newType
      if (name == "逻辑判断") {
        this.getLJPDINFO(seq)
      }
      this.getDeviceModelList(seq)
    },
    async getModeTypeList () {
      const { status, success, object, message } = await queryProjectAllUser()
      if (status == "200") {
        this.workModelTypeList = object
      }
    },
    saveQZTJ (val) {

      this.formateArrObjData(this.zjList, val, "seq")
      // this.zjList.push(val)

      this.dialogVisible = false
    },
    formateArrObjData (initialArr, obj, pro) {
      // 判定数据是否为数组
      if (!(initialArr instanceof Array)) {
        return []                        //'请传入正确格式的数组'
      }
      // 判定数据是否为对象
      if (!(obj instanceof Object)) {
        return []                        //'请传入正确格式的对象'
      }
      if (!pro) {
        return []                        //'请传入正确格式的属性名'（用于判断的key值）
      }

      let index = initialArr.findIndex((val) => val[pro] === obj[pro])
      let tempArr = initialArr
      // 如果有就替换  没有就添加
      if (initialArr.findIndex((val) => val[pro] === obj[pro]) !== -1) {
        tempArr.splice(index, 1, obj)
      } else {
        tempArr.push(obj)
      }
      return tempArr
    },
    handleClose (done) {
      done()
    },
    //设置默认前置条件
    async getData () {
      const { status, success, object, message } = await queryMyWorkModelOne({ workModelCode: this.workModelCode })
      let statusList = [{ id: "nodeKG1t338a2DnXf3Ne", status: 0 }, {
        id: "nodetLBsrIrG3i4rX3nZ",
        status: 1
      }, { id: "nodeGAeMJHVwCPh0PG3m", status: 2 }]
      if (status == 200) {
        let { nodeList, linkList, workForm } = JSON.parse(object.location)

        this.nodeList = this.arrMergeStatus(nodeList, statusList, "id")
        console.log(this.nodeList)
        this.linkList = linkList
        this.workForm = workForm
        this.mapString = object.before
      }
      // this.nodeList = [{ "id": "nodeVsWhMqMnYaHGGAXk", "width": 140, "height": 70, "coordinate": [552, 106.09375], "meta": { "desc": "{\"deviceModelName\":\"测试枚举参数模型\",\"deviceModelCode\":\"SBMX06232841263\"}", "label": "open", "code": "MD_OPEN", "name": "模型开启", "type": "open", "placeholder": "模型开启", "DataId": "1687580878174" } }, { "id": "nodeCzZ0Fjf3me1aRJBX", "width": 140, "height": 70, "coordinate": [453, 276.09375], "meta": { "desc": "[{\"parValue\":\"项位\",\"parKey\":\"MJONE.LO\",\"seqValue\":\"15\",\"deviceModelCode\":\"SBMX06232841263\",\"deviceModelName\":\"测试枚举参数模型\"}]", "label": "update", "code": "MD_CHANGE", "name": "模型参数修改", "type": "update", "placeholder": "模型参数修改", "DataId": "1687580891862" } }, { "id": "node7RMArDkYux8i3Uco", "width": 140, "height": 70, "coordinate": [827, 258.09375], "meta": { "desc": "{\"deviceModelName\":\"断路器1型\",\"deviceModelCode\":\"SBMX06135846149\"}", "label": "close", "code": "MD_CLOSE", "name": "模型关闭", "type": "close", "placeholder": "模型关闭", "DataId": "1687580902415" } }]
      // this.linkList = [{ "id": "linkQS1D29gnDv1Vw6Mg", "startId": "nodeVsWhMqMnYaHGGAXk", "endId": "nodeCzZ0Fjf3me1aRJBX", "startAt": [70, 70], "endAt": [70, 0], "meta": { "desc": "15" } }, { "id": "linkhDrCodEiR845YfGx", "startId": "nodeCzZ0Fjf3me1aRJBX", "endId": "node7RMArDkYux8i3Uco", "startAt": [140, 35], "endAt": [0, 35], "meta": { "desc": "18" } }]
    },
    arrMergeStatus (arr1, arr2, key) {
      const combined = arr1.map((item1) => {
        arr2.map((item2) => {
          if (item1[key] === item2[key]) {
            Object.assign(item1.meta, item2)
          }
        })
        return item1
      })
      return combined
    },
    //设置默认前置条件
    async getSysData () {
      const { status, success, object, message } = await querySysWorkModelOne({ workModelCode: this.workModelCode })
      if (status == 200) {
        let { nodeList, linkList, workForm } = JSON.parse(object.location)
        this.nodeList = nodeList
        this.linkList = linkList
        this.workForm = workForm
        this.mapString = object.before
      }
      // this.nodeList = [{ "id": "nodeVsWhMqMnYaHGGAXk", "width": 140, "height": 70, "coordinate": [552, 106.09375], "meta": { "desc": "{\"deviceModelName\":\"测试枚举参数模型\",\"deviceModelCode\":\"SBMX06232841263\"}", "label": "open", "code": "MD_OPEN", "name": "模型开启", "type": "open", "placeholder": "模型开启", "DataId": "1687580878174" } }, { "id": "nodeCzZ0Fjf3me1aRJBX", "width": 140, "height": 70, "coordinate": [453, 276.09375], "meta": { "desc": "[{\"parValue\":\"项位\",\"parKey\":\"MJONE.LO\",\"seqValue\":\"15\",\"deviceModelCode\":\"SBMX06232841263\",\"deviceModelName\":\"测试枚举参数模型\"}]", "label": "update", "code": "MD_CHANGE", "name": "模型参数修改", "type": "update", "placeholder": "模型参数修改", "DataId": "1687580891862" } }, { "id": "node7RMArDkYux8i3Uco", "width": 140, "height": 70, "coordinate": [827, 258.09375], "meta": { "desc": "{\"deviceModelName\":\"断路器1型\",\"deviceModelCode\":\"SBMX06135846149\"}", "label": "close", "code": "MD_CLOSE", "name": "模型关闭", "type": "close", "placeholder": "模型关闭", "DataId": "1687580902415" } }]
      // this.linkList = [{ "id": "linkQS1D29gnDv1Vw6Mg", "startId": "nodeVsWhMqMnYaHGGAXk", "endId": "nodeCzZ0Fjf3me1aRJBX", "startAt": [70, 70], "endAt": [70, 0], "meta": { "desc": "15" } }, { "id": "linkhDrCodEiR845YfGx", "startId": "nodeCzZ0Fjf3me1aRJBX", "endId": "node7RMArDkYux8i3Uco", "startAt": [140, 35], "endAt": [0, 35], "meta": { "desc": "18" } }]
    },
    setDefaultNode () {
      this.nodeList = [{
        coordinate: [(this.$refs.flowContainer.offsetWidth - 140) / 2, (this.$refs.flowContainer.offsetHeight -
          70) / 2 - this.$refs.flowContainer.offsetHeight * 0.3],
        height: 70,
        width: 140,
        id: "nodeX54nlZtoRkhGTkoe",
        meta: {
          desc: "",
          label: "start",
          name: "前置条件",
          placeholder: "请添加前置条件",
          type: "start"
        }

      }]
    },
    //点击节点
    cliNode (meta) {

      if (meta.DataId) {
      } else {
        meta.DataId = new Date().getTime().toString()
      }
      this.flowId = meta.DataId
      this.capList = meta.desc
      this.$refs.drawerApprove.isDrawer = true
      this.$refs.drawerApprove.openType = meta.type
      // this.$refs.drawerApprove.listData = meta.desc
    },

    linkDesc (link) {
      return link.meta ? link.meta.desc : ""
    },
    settingSubmit () {
      const conf = this.drawerConf
      if (this.drawerConf.type === drawerType.node) {
        if (!conf.info.meta) conf.info.meta = {}
        Object.keys(this.nodeSetting).forEach(key => {
          this.$set(conf.info.meta, key, this.nodeSetting[key])
        })
        this.$refs.nodeSetting.resetFields()
      } else {
        if (!conf.info.meta) conf.info.meta = {}
        Object.keys(this.linkSetting).forEach(key => {
          this.$set(conf.info.meta, key, this.linkSetting[key])
        })
        this.$refs.linkSetting.resetFields()
      }
      conf.visible = false
    },
    docMousemove ({
      clientX,
      clientY
    }) {
      const conf = this.dragConf
      if (conf.isMove) {
        conf.ele.style.top = clientY - conf.offsetTop + "px"
        conf.ele.style.left = clientX - conf.offsetLeft + "px"
      } else if (conf.isDown) {
        // 鼠标移动量大于 5 时 移动状态生效
        conf.isMove = Math.abs(clientX - conf.clientX) > 5 || Math.abs(clientY - conf.clientY) > 5
      }
    },
    docMouseup ({
      clientX,
      clientY
    }) {
      const conf = this.dragConf
      conf.isDown = false

      if (conf.isMove) {
        const {
          top,
          right,
          bottom,
          left
        } = this.$refs.flowContainer.getBoundingClientRect()

        // 判断鼠标是否进入 flow container
        if (
          clientX > left && clientX < right && clientY > top && clientY < bottom
        ) {
          // 获取拖动元素左上角相对 super flow 区域原点坐标
          const coordinate = this.$refs.superFlow.getMouseCoordinate(
            clientX - conf.offsetLeft,
            clientY - conf.offsetTop
          )
          // 添加节点
          this.$refs.superFlow.addNode({
            coordinate,
            ...conf.info
          })
        }
        conf.isMove = false
      }
      if (conf.ele) {
        conf.ele.remove()
        conf.ele = null
      }
    },
    nodeItemMouseDown (evt, infoFun) {
      const {
        clientX,
        clientY,
        currentTarget
      } = evt

      const {
        top,
        left
      } = evt.currentTarget.getBoundingClientRect()

      const conf = this.dragConf
      const ele = currentTarget.cloneNode(true)

      Object.assign(this.dragConf, {
        offsetLeft: clientX - left,
        offsetTop: clientY - top,
        clientX: clientX,
        clientY: clientY,
        info: infoFun(),
        ele,
        isDown: true
      })

      ele.style.position = "fixed"
      ele.style.margin = "0"
      ele.style.top = clientY - conf.offsetTop + "px"
      ele.style.left = clientX - conf.offsetLeft + "px"

      this.$el.appendChild(this.dragConf.ele)
    },
    handleRulesSLJ () {
      this.$refs["ruleform"].validate((valid) => {
        if (valid) {
          this.saveSLH()
        } else {
          return false
        }
      })
    },
    async saveSLH () {
      let data = {
        newCode: this.$route.query.newCode,
        newName: this.slhinfoData.newName,
        projectCode: this.$route.query.projectCode,
        workModelCode: this.$route.query.workModelCode,
        userCodes: this.slhinfoData.userCodes.join("&"),
        zjList: this.zjList
      }
      if (this.$route.query.status == 0) {
        const res = await insertWorkNewOne({ param: JSON.stringify(data) })
        if (res.status == 200) {
          this.returnUrl()
          this.$message({
            type: "success",
            message: res.message
          })
        }
      } else {
        const res = await updateWorkNewOne({ param: JSON.stringify(data) })
        if (res.status == 200) {
          this.returnUrl()
          this.$message({
            type: "success",
            message: res.message
          })
        }
      }

    },

    saveMessage (obj) {
      this.$refs.drawerApprove.openType = ""
      this.$refs.drawerApprove.isDrawer = false
      let index = this.flowMessages.findIndex((item) => item.DataId === obj.DataId)
      // 如果有就替换，没有就添加
      if (index !== -1) {
        this.flowMessages.splice(index, 1, obj)
      } else {
        this.flowMessages.push(obj)
      }
      this.nodeList = this.$refs.superFlow.toJSON().nodeList
      this.flowValue = this.arrMerge(this.nodeList, this.flowMessages, "DataId")
      this.nodeList = JSON.parse(JSON.stringify(this.flowValue))
    },
    //数组数据和点位合并
    arrMerge (arr1, arr2, key) {
      const combined = arr1.map((item1) => {
        arr2.map((item2) => {
          if (item1.meta[key] === item2[key]) {
            Object.assign(item1.meta, item2)
          }
        })
        return item1
      })
      return combined
    },
    //线数据和点位合并
    arrMergeline (arr1, arr2) {
      const combined = arr1.map((item1) => {
        arr2.map((item2) => {
          if (item1.id === item2.endId) {
            Object.assign(item1.meta, item2)
          }
        })
        return item1
      })
      return combined
    },
    returnUrl () {
      this.$router.go(-1)
    },
    async test () {
      this.linkList = this.$refs.superFlow.toJSON().linkList
      let arr1 = JSON.parse(JSON.stringify(this.flowValue))
      let arr2 = JSON.parse(JSON.stringify(this.linkList))
      let newArr = this.arrMergeline(arr1, arr2)

      let children = []
      newArr.forEach(element => {
        children.push({
          seq: element.id,
          modelModuleCode: element.meta.code,
          detail: element.meta.desc ? element.meta.desc : null,
          resultStatus: element.meta.hasOwnProperty("meta") ? (element.meta.meta ? element.meta.meta.desc : null) : null,
          fatherSeq: element.meta.startId ? element.meta.startId : null
        })
      })
      if (this.$route.query.type == 0) {
        let param = {
          ...this.workForm,
          location: JSON.stringify({
            nodeList: this.nodeList,
            linkList: this.linkList,
            workForm: this.workForm
          }),
          before: JSON.stringify(this.mapString),
          children: JSON.stringify(children)
        }

        const res = await addMyWorkModel({ param: JSON.stringify(param) })
        if (res.status == 200) {
          this.returnUrl()
          this.$message({
            type: "success",
            message: res.message
          })
        }
      } else {
        let param = {
          ...this.workForm,
          location: JSON.stringify({
            nodeList: this.nodeList,
            linkList: this.linkList,
            workForm: this.workForm
          }),
          workModelCode: this.workModelCode,
          before: JSON.stringify(this.mapString),
          children: JSON.stringify(children)
        }

        const res = await updateMyWorkModelOne({ param: JSON.stringify(param) })
        if (res.status == 200) {
          this.returnUrl()
          this.$message({
            type: "success",
            message: res.message
          })
        }
      }

    },
    async saveMyFlow () {
      const res = await addMyWorkFromSys({ workModelCode: this.workModelCode })
      if (res.status == 200) {
        this.returnUrl()
        this.$message({
          type: "success",
          message: res.message
        })
      }
    },
    getDeviceModelList (seq) {
      this.selectList = this.selectOveryList[seq]

    },
    saveLogic () {
      let str = this.selectList.map(v => v.value).join("&")
      let array = {
        newType: this.dialogNewType,
        seq: this.dialogSeq,
        newValues: str
      }
      this.saveQZTJ(array)
    }
  }
}
</script>

<style lang="scss" scoped>
.module-item {
  height: 110px;
  width: 110px;

  .item {
    // background-color: #D7D7D7;
  }
}

.tab-left {
  top: 10px;
  width: 280px;
  z-index: 100 !important;
}

::v-deep .el-drawer__header {
  margin-bottom: 0;
}

.workflow-container {
  width: calc(100vw - 80px);
  height: calc(100vh - 128px);
  box-shadow: 0px 3px 1px -2px rgb(0 0 0 / 20%), 0px 2px 2px 0px rgb(0 0 0 / 14%), 0px 1px 5px 0px rgb(0 0 0 / 12%);
  margin: 32px;
  padding: 0;
  background: #fff;
  overflow: hidden;
}

.ellipsis {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-wrap: break-word;
}

.super-flow-demo {
  // position: relative;
  // margin: 20px;
  // background: #f5f5f5;
  height: calc(100vh - 50px);

  .node-container {
    width: 100%;
    height: 50px;
    background-color: #FFFFFF;

    .node-item {
      display: inline-block;
      font-size: 14px;
      height: 30px;
      width: 120px;
      margin: 0 20px 0 0;
      background: #FFFFFF;
      line-height: 30px;
      box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.3);
      cursor: pointer;
      user-select: none; // 防止鼠标左键拖动选中页面的文字
      text-align: center;

      &:hover {
        box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.4);
      }
    }
  }

  .flow-container {
    width: 100%;
    height: calc(100%);

    .super-flow {
      overflow: auto;
    }
  }

  .saveIcon {
    position: absolute;
    right: 0px;
    top: 0px;
  }

  .super-flow__node {
    .flow-node {
      box-sizing: border-box;
      width: 100%;
      height: 100%;
      // line-height: 40px;
      // padding: 0 6px;
      font-size: 14px;
      // color: #fff;
      // font-weight: bold;

      .node-content {
        text-align: center;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .ellipsis.flow-node-item {
    background: #fff;
    border-radius: 4px;
    border: 1px solid #E6E6E6;
  }

  /*开始节点样式*/
  .ellipsis.flow-node-start {
    background: #55ABFC;
    border-radius: 10px;
    border: 1px solid #b4b4b4;
  }

  /*流程节点样式*/
  .ellipsis.flow-node-process {
    position: relative;
    background: #30B95C;
    border: 1px solid #b4b4b4;
  }

  /*条件节点样式*/
  .ellipsis.flow-node-if {
    width: 120px;
    height: 120px;
    position: relative;
    top: 24px;
    left: 24px;
    background: #BC1D16;
    border: 1px solid #b4b4b4;
    transform: rotateZ(45deg); //倾斜

    .node-content {
      position: absolute;
      top: 50%;
      left: 20px;
      width: 100%;
      transform: rotateZ(-45deg) translateY(-75%);
    }
  }

  /*结束节点样式*/
  .ellipsis.flow-node-end {
    background: #000;
    border-radius: 10px;
    border: 1px solid #b4b4b4;
  }
}

.top-div {
  position: absolute;
  width: 280px;
  height: 450px;
  margin: 10px;
  top: 10px;
  z-index: 2;
}

.div-moudle {
  position: absolute;
  width: 320px;
  height: 600px;
  left: 10px;
  top: 110px;
}

.select-botton {
  position: absolute;
  top: 60px;
  left: 30px;
  z-index: 2;
}

.right-box {
  position: absolute;
  left: 10px;
}

::v-deep .el-card__body {
  padding: 20px 10px !important;
}

.node-title {
  position: relative;

  img {
    position: absolute;
    right: 10px;
  }
}

.silclass {
  display: block;
  width: 100%;
  text-align: center;
  margin-bottom: 15px;
}
</style>
<style>
.super-flow-demo .super-flow__node {
  border: none;
  background: none;
  box-shadow: none;
}
</style>
